package org.linlinjava.litemall.admin.service;

import com.alibaba.product.param.AlibabaProductProductAttribute;
import com.alibaba.product.param.AlibabaProductProductInfo;
import com.alibaba.product.param.AlibabaProductProductSKUInfo;
import com.alibaba.product.param.AlibabaProductSKUAttrInfo;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.admin.alibaba.vo.AlibabaMessageGoodsSkuVo;
import org.linlinjava.litemall.admin.dto.GoodsAllinone;
import org.linlinjava.litemall.core.config.GlobalConfig;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

@Service
public class AlibabaGoodsChangeService {
    private final Log logger = LogFactory.getLog(AlibabaGoodsChangeService.class);

    @Autowired
    private LitemallGoodsService goodsService;
    @Autowired
    private LitemallGoodsSpecificationService specificationService;
    @Autowired
    private LitemallGoodsAttributeService attributeService;
    @Autowired
    private LitemallGoodsProductService productService;
    @Autowired
    private LitemallCategoryService categoryService;
    @Autowired
    private LitemallBrandService brandService;
    @Autowired
    private ProductLibriaryService productLibriaryService;
    @Autowired
    private ProductsService productsService;

    private String message;

    public void setMessage(String message) {
        this.message = message;
    }

    public String getMessage() {
        return message;
    }

    public Boolean skuMessageChangeResult(AlibabaMessageGoodsSkuVo vo){
        Boolean flag = false;
        LitemallGoodsProduct product  = new LitemallGoodsProduct();
        product.setAlibabaSkuid(vo.getSkuId());
        product.setNumber(Integer.valueOf(vo.getSkuOnSale()));
        product.setAlibabaProductid(Long.valueOf(vo.getOfferId()));

        if(productService.updateByMessage(product)==0)
            flag = true;

        return flag;

    }
    /**
     *
     * 查询所有品类库列表
     * */
    public List<ProductLibrrary> productLibrarylist(){
        return productLibriaryService.getAll();

    }
    /**
     *
     * 根据类库id查询此类库下商品
     * */

    public List<Products> productListByLibraryId(Long libraryId,Integer status,Integer page,Integer size){

        return productsService.getProductByProductId(libraryId, status,page,size);
    }

    public Integer getNumTotal(Long libraryId,Integer status){
        return productsService.getProductCount(libraryId, status);
    }
    public void updateProducts(Long productId){
        Products products = productsService.getProductOneByOfferId(productId.toString());
        if(products!=null&&products.getStatus()!=2)
            products.setStatus(2);
            productsService.update(products, productId.toString());

    }

    @Transactional
    public int alibabaGoodsOrmGoods(AlibabaProductProductInfo productInfo,Float franking,Boolean selfPrice,Long categoryId){
        int flag = 1;

        if(productInfo==null){
               return 0;
        }

        LitemallGoods goods = new LitemallGoods();
        Integer goodsSn = Integer.valueOf(goodsService.getGoodsMaxGoodsn().getGoodsSn())+1 ;
        goods.setGoodsSn(goodsSn.toString());
        goods.setIsOnSale(false);
        goods.setSortOrder(Short.parseShort("101"));
        goods.setIsNew(false);
        goods.setIsHot(false);
        goods.setDeleted(false);
        goods.setAdminid(1);
        goods.setCategoryId(categoryId.intValue());

       // goods.setCategoryId(1002000);
        //以上是默认值
        goods.setName(productInfo.getSubject());
        goods.setGallery(productInfo.getImage().getImages());
        goods.setBrief(productInfo.getSubject());
        //发现规律一般白底的图片都是主图最后一张
        goods.setPicUrl(productInfo.getImage().getImages().length>0?productInfo.getImage().getImages()[productInfo.getImage().getImages().length-1]:null);
        goods.setUnit(productInfo.getSaleInfo().getUnit());
        goods.setMinorderquantity(productInfo.getSaleInfo().getMinOrderQuantity());


        //设置专卖店价格为建议零售价(1.2+0-1的随机数）的倍数
//        if(productInfo.getSaleInfo().getRetailprice()!=null&&productInfo.getSaleInfo().getRetailprice()>)
//            goods.setCounterPrice(BigDecimal.valueOf(productInfo.getSaleInfo().getRetailprice()));
//
//        if(productInfo.getSaleInfo().getRetailprice()!=null&&!selfPrice) {
//            goods.setRetailPrice( BigDecimal.valueOf(productInfo.getSaleInfo().getRetailprice()) );
//        }else {
//            if ( productInfo.getSaleInfo().getPriceRanges().length > 0) {
//                goods.setRetailPrice(BigDecimal.valueOf((productInfo.getSaleInfo().getPriceRanges()[0].getPrice() + franking) * 1.2));
//            }
//        }

        /**
         * 价格算法
         * 1.有sku信息商品：进货价格从sku里面取
         * 2、无sku信息商品，价格基数从saleinfo 里面取
         *
         * 1.1 建议零售价>进货价*1.3+8，
         *          1.1.1专柜价=建议零售价
         *          1.1.2 销售价格 = 进货价*1.3+8，分sku取，goods表，从sku价格表第一条取值
         *
         * 1.2 建议零售价<= 进货价*1.3+8
         *          1.2.1 专柜价格=0
         *          1.2.2 销售价格=进货价*1.3+8,分sku进行取值，goods表价格，取sku第一条
         * 2.1 建议零售价 > 进货价*1.3+8
         *          2.1.1 专柜价格=建议零售价
         * 2.2建议零售价 <= 进货价*1.3+8
         *          2.2.1 专柜价格= 0
         *
         *
         * 分销基准价+8 的8 是设置的默认邮费 8元
         * */
        if(productInfo.getSaleInfo().getQuoteType()==0){
            //无sku信息。按照数量报价商品productInfo.getSaleInfo().getConsignPrice()
            goods.setRetailPrice(this.priceAuto(productInfo.getSaleInfo().getConsignPrice()));
            goods.setPrimeCost(BigDecimal.valueOf(productInfo.getSaleInfo().getConsignPrice()));
            if(productInfo.getSaleInfo().getRetailprice()>goods.getRetailPrice().doubleValue())
                    goods.setCounterPrice(BigDecimal.valueOf(productInfo.getSaleInfo().getRetailprice()));

        }else {
            // 1 和 2 有sku信息，按照sku取值报价
            //productInfo.getSaleInfo().getPriceRanges()[0].getPrice()
           if(productInfo.getSaleInfo().getPriceRanges().length>0){
               goods.setRetailPrice(this.priceAuto(productInfo.getSaleInfo().getPriceRanges()[0].getPrice()));
               goods.setPrimeCost(BigDecimal.valueOf(productInfo.getSaleInfo().getPriceRanges()[0].getPrice()));
               if(productInfo.getSaleInfo().getRetailprice()!=null&&(productInfo.getSaleInfo().getRetailprice()>goods.getRetailPrice().doubleValue()))
                   goods.setCounterPrice(BigDecimal.valueOf(productInfo.getSaleInfo().getRetailprice()));
               //productInfo.getSaleInfo().getPriceRanges()[0].getPrice()

           }else {
               logger.info("未获取到价格区间，修改取值规则");
           }
        }

        //从阿里巴巴获取的商品描述直接写入，需要人工修改后方可出售
        goods.setDetail(productInfo.getDescription());
       // goods.setPrimeCost(productInfo.getSaleInfo().getPriceRanges().length>0?BigDecimal.valueOf(productInfo.getSaleInfo().getPriceRanges()[0].getPrice()):BigDecimal.valueOf(0));
        //goods.setFreight(BigDecimal.valueOf(productInfo.getShippingInfo().getUnitWeight()));

        goods.setAlibabaProductid(productInfo.getProductID());
        goods.setMainVedio(productInfo.getMainVedio());
        goods.setQualitylevel(productInfo.getQualityLevel().toString());
        goods.setSupplierloginid(productInfo.getSellerLoginId());
        flag=goodsService.validAndAdd(goods);
        if(flag==0){
            this.setMessage("此商品已经同步过，无需再次执行");
            logger.info("此商品已经同步过，无需再次执行");
            return flag;
        }
        goods = goodsService.getGoodsMaxGoodsn();
        /**
         * 商品表映射完成
         * 开始映射goods_product 和goods_specificatil
         * */

        for(AlibabaProductProductSKUInfo skuinfo:productInfo.getSkuInfos()){
               // goodsProduct = null;
            LitemallGoodsProduct goodsProduct = new LitemallGoodsProduct();
            LitemallGoodsSpecification goodsSpecification =new LitemallGoodsSpecification();
            ArrayList<String> list  = new ArrayList<String>();
            ArrayList<String> namelist  = new ArrayList<String>();
            String url = null;
                for(AlibabaProductSKUAttrInfo skuAttr :skuinfo.getAttributes()){
                    //goodsSpecification = null;
                    goodsSpecification.setGoodsId(goods.getId());
                    goodsSpecification.setSpecification(skuAttr.getAttributeName());
                    goodsSpecification.setValue(skuAttr.getAttributeValue());
                    goodsSpecification.setDeleted(false);
                    if(skuAttr.getSkuImageUrl()!=null){
                        url=skuAttr.getSkuImageUrl();
                        goodsSpecification.setPicUrl(skuAttr.getSkuImageUrl());
                    }
                    specificationService.validAndAdd(goodsSpecification);
                    list.add(skuAttr.getAttributeValue());
                    namelist.add(skuAttr.getAttributeName());
                }
            String[] strings = new String[list.size()];
                String[]  nameString = new String[namelist.size()];
            goodsProduct.setGoodsId(goods.getId());
            goodsProduct.setSpecifications(list.toArray(strings));
            goodsProduct.setSpecificationName(namelist.toArray(nameString));

            /**
             *
             * 设置sku的进货价格和销售价格
             * 没有sku信息，从productinfo中取 分销基准价
             * 有sku信息  从sku中取分销基准价
             * **/
            if(productInfo.getSaleInfo().getQuoteType()==0){
                goodsProduct.setPrice(goods.getRetailPrice());
                goodsProduct.setCostPrice(goods.getPrimeCost());
            }else {
                //skuinfo.getConsignPrice()
                goodsProduct.setPrice(this.priceAuto(skuinfo.getConsignPrice()));
                goodsProduct.setCostPrice(BigDecimal.valueOf(skuinfo.getConsignPrice()));
            }




            goodsProduct.setNumber(skuinfo.getAmountOnSale());
            goodsProduct.setUrl(url);
            goodsProduct.setMinorderquantity(productInfo.getSaleInfo().getMinOrderQuantity());
            goodsProduct.setDeleted(false);
            goodsProduct.setAlibabaSkuid(skuinfo.getSkuId().toString());
            goodsProduct.setAlibabaSpecid(skuinfo.getSpecId());
            goodsProduct.setAlibabaProductid(productInfo.getProductID());

            productService.add(goodsProduct);
            /**
             * 商品规格表映射完
             * */

            for(AlibabaProductProductAttribute attribute:productInfo.getAttributes()){
                if(!this.checkAttributes(attribute.getAttributeName())){
                    LitemallGoodsAttribute litemallattribute =new LitemallGoodsAttribute();
                    litemallattribute.setGoodsId(goods.getId());
                    litemallattribute.setAttribute(attribute.getAttributeName());
                    litemallattribute.setValue(attribute.getValue());
                    litemallattribute.setDeleted(false);
                    attributeService.validAndAdd(litemallattribute);
                }

            }

        }
        this.setMessage("商品同步成功");
        /**
         * products表设置为已经同步
         * */
        Products products = productsService.getProductOneByOfferId(productInfo.getProductID().toString());
        products.setStatus(1);
        productsService.update(products, productInfo.getProductID().toString());

        return flag;
    }
    private BigDecimal priceAuto(Double costPrice){
        /**
         * 价格算法
         * 入参：分销基准价
         * 出参:销售价格
         * 分销基准价<20   +2
         *          <50   +3
         *          <100  +5
         *          <200  +10
         *          >=200  +15
         * **/
        if(costPrice<20){
            //分销基准价小于100
            return BigDecimal.valueOf(costPrice+2);
        }else if(costPrice<50&&costPrice>=20){
            //分销基准价在100~ 200之间
            return BigDecimal.valueOf(costPrice+3);
        }else if(costPrice<100&&costPrice>=50){
            //分销基准价在100~ 200之间
            return BigDecimal.valueOf(costPrice+5);
        }else if(costPrice<200&&costPrice>=100){
            //分销基准价在100~ 200之间
            return BigDecimal.valueOf(costPrice+10);
        }else{
            //分销基准价大于200
            return BigDecimal.valueOf(costPrice+15);
        }
    }
    public Boolean checkAttributes(String strValue){
        for(int i =0;i< GlobalConfig.ArrtibutesArr.length;i++){
            if (strValue.equals(GlobalConfig.ArrtibutesArr[i])){
                return true;
            }
        }
        return false;
    }


}
